import {
    Component,
    OnInit,
    Injector,
    ViewChild,
    Input,
    ViewEncapsulation,
    Output,
    EventEmitter,
    ElementRef
} from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';

import { CreateOrEditMarkBaseInfoModalComponent } from './create-or-edit-mark-baseinfo-modal.component';
import {
    StockZT_BaseInfoServiceProxy,
    Stock_BIMarketListDto,
    ListDtoExtensionsItem,
    StockType,
    Stock_MarketBaseInfoImportExcelDto,
    Stock_MarketBaseInfoImportExcelOutput
} from '@shared/service-proxies/stock-service-proxies';
@Component({
    templateUrl: './mark-basefield.component.html',
    animations: [appModuleAnimation()],
    selector: 'mark-base-field',
    encapsulation: ViewEncapsulation.None
})
export class MarkBaseFieldComponent extends AppComponentBase implements OnInit {
    @Input() set canedit(val) {
        if (val) {
            this._edit = val;
        }
    }
    constructor(injector: Injector, private _baseInfoServiceProxy: StockZT_BaseInfoServiceProxy) {
        super(injector);
    }
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('createOrEditBaseInfoModal') createOrEditBaseInfoModal: CreateOrEditMarkBaseInfoModalComponent;
    @ViewChild('stockbasediv') stockbasediv: ElementRef;
    _edit;

    @Output() modalSelect = new EventEmitter<Stock_BIMarketListDto>();
    @Output() markBaseHeight = new EventEmitter<number>();
    @Output() dataLoad: EventEmitter<any> = new EventEmitter<any>();
    anyncing = false;
    filterText = '';
    f_MaterialCode;
    f_MaterialName;
    f_DimensionGroup;
    f_PrimaryVendorId;
    f_CAL_Manufacturer;
    f_TradeMark;
    f_Station;
    f_TecCondition;
    f_Specification;
    f_QualityLevel;
    f_DimensionGroupOptions;
    codeItemId;
    codeName;
    selectedValue: Stock_BIMarketListDto;
    extensions: Array<ListDtoExtensionsItem>;
    f_CAL_ItemPrecision;
    // f_CAL_ItemHardDegree;
    f_UnitId;
    ngOnInit() {
        // this._baseInfoServiceProxy.getAllDimension().subscribe(result => {
        //     this.f_DimensionGroupOptions = result.map(e => {
        //         return {
        //             label: e.f_Name,
        //             value: e.f_Name
        //         };
        //     });
        // });
    }

    rowSelect() {
        this.modalSelect.emit(this.selectedValue);
    }
    delete(id) {
        console.log(this.selectedValue);
        if (!this.selectedValue) {
            this.notify.error(this.l('请选择要删除的信息'));
        } else {
            this.message.confirm('确认删除该条数据吗？', isConfirmed => {
                if (isConfirmed) {
                    this._baseInfoServiceProxy.deleteBaseInfo(id).subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBaseField();
                    });
                }
            });
        }
    }
    onUpload(event) {
        // let list = event as Array<any>;
        let list = event.fileData[0].sheetJson;
        console.log(list)
        let customerImportIntoList = list.map(el => {
            return {
                f_MaterialCode: el.物料编码,
                f_MaterialName: el.物料名称,
                f_StockType: el.物料组,
                f_DimensionGroup: el.管理维度,
                f_UnitId: el.计量单位,
                f_Specification: el.规格,
                f_TradeMark: el.牌号,
                f_CAL_ItemPrecision: el.精度,
                f_CAL_ItemHardDegree: el.硬度,
                f_CAL_ItemShape: el.形状,
                f_CAL_ItemBond: el.结合剂,
                f_CAL_ItemStopDay: el.油封保存期限,
                f_CAL_ItemBorrowDay: el.借用期限,
                f_CAL_ItemRemark: el.备注,
                f_DimensionGroupID: null
            };
        }) as Array<Stock_MarketBaseInfoImportExcelDto>;
        this.message.confirm(
            '确认导入这' + list.length + '条数据吗？',
            this.l('AreYouSure'),
            async (isConfirmed) => {
                if (isConfirmed) {
                    // this.primengTableHelper.showLoadingIndicator();
                    abp.ui.setBusy(undefined, `0 / ${customerImportIntoList.length}`);
                    let errorList = new Array<Stock_MarketBaseInfoImportExcelOutput>()
                    let currentIndex = 0
                    const IMPORT_STEP_LENGTH = 10
                    while (currentIndex < customerImportIntoList.length) {
                        let currentStepLength = IMPORT_STEP_LENGTH
                        if (customerImportIntoList.length - currentIndex < IMPORT_STEP_LENGTH) {
                            currentStepLength = customerImportIntoList.length - currentIndex
                        }
                        let result = await this.uploadStep(customerImportIntoList.slice(currentIndex, currentIndex + currentStepLength))
                        if (result && result.length > 0) {
                            errorList = errorList.concat(result)
                        }
                        currentIndex += currentStepLength
                        abp.ui.setBusy(undefined, `${currentIndex} / ${customerImportIntoList.length}`);
                        console.log(`导入进度：${currentIndex} / ${customerImportIntoList.length}`)
                    }
                    abp.ui.clearBusy();
                    if (errorList.length > 0) {
                        //导出数据
                        console.log(errorList)
                        this.notify.error('部分导入成功');
                    } else {
                        this.notify.success('导入数据成功');
                    }
                    //加载数据
                    this.getBaseField()
                    // this.primengTableHelper.hideLoadingIndicator();
                }
            }
        );
    }
    uploadStep(list: Array<Stock_MarketBaseInfoImportExcelDto>) {
        return new Promise<Stock_MarketBaseInfoImportExcelOutput[]>((resolve, reject) => {
            this._baseInfoServiceProxy
                .stock_MarkBaseInfoImportExcel(list)
                .subscribe(result => {
                    resolve(result)
                });
        })
    }
    clearquery() {
        this.filterText = '';
        this.f_MaterialCode = '';
        this.f_MaterialName = '';
        this.f_DimensionGroup = '';
        this.f_PrimaryVendorId = '';
        this.f_CAL_Manufacturer = '';
        this.f_TradeMark = '';
        this.f_Station = '';
        this.f_TecCondition = '';
        this.f_Specification = '';
        this.f_QualityLevel = '';
        this.codeName = '';
        this.f_CAL_ItemPrecision = '';
        // this.f_CAL_ItemHardDegree = '';
        this.f_UnitId = '';
    }
    sysData() {
        this.primengTableHelper.showLoadingIndicator();
        
    }
    getBaseField(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            this.paginator.changePage(0);
            return;
        }

        this.primengTableHelper.showLoadingIndicator();
        this._baseInfoServiceProxy
            .getBaseFieldListExtentionByCode(
                this.filterText,
                this.f_MaterialCode,
                this.f_MaterialName,
                this.f_PrimaryVendorId,
                this.f_CAL_Manufacturer,
                this.f_TradeMark,
                this.f_Station,
                this.f_TecCondition,
                this.f_Specification,
                this.f_QualityLevel,
                this.f_DimensionGroup,
                this.f_CAL_ItemPrecision,
                undefined,
                this.f_UnitId,
                StockType.市采,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_BaseFieldListDto.totalCount;
                this.primengTableHelper.records = result.stock_BaseFieldListDto.items;
                this.primengTableHelper.hideLoadingIndicator();
                setTimeout(() => {
                    this.dataLoad.emit(this.stockbasediv.nativeElement.clientHeight - 18);
                }, 250);
            });
    }
}
